package com.tanker.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tanker.common.ErrorCode;
import com.tanker.common.out.ResponseObject;
import com.tanker.model.Oauth2Token;
import com.tanker.service.car.UserInfoService;
import com.tanker.util.wxx.SignUtil;
import com.tanker.util.wxx.WxConfig;



/**
 * @author xqxue
 * @time 2017年11月20日 下午6:51:06
 */
@Controller
@RequestMapping("/wx/")
public class WechatController {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatController.class);
	/** 授权地址 */
	public static final String AUTHORIZE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize";
    @Autowired
    private WxConfig wxConfig;
	@Autowired
	private UserInfoService userInfoService;
    
//    @ResponseBody
//	@RequestMapping(value = "/getConfig", method = RequestMethod.POST)
//	public ResponseObject<?> getConfig(HttpServletRequest request) {
//		logger.info("前端开始获得通行证");
//		
//		String url = request.getParameter("url");
//		if(StringUtils.isBlank(url)) {
//			logger.error("getConfig url is null!");
//			return new ResponseObject<String>(ErrorCode.FAILED, "url is null");
//		}
//		ErrorCode error = ErrorCode.SUCCESS;
//		
//		WxJsapiSignature sign = jsApiService.createJsapiSignature(url);
//		logger.info("前端开始获得通行证结束");
//		return new ResponseObject<WxJsapiSignature>(error, sign);
//	}
    
    /**
	 * 微信网页授权
	 */
	@RequestMapping(value = "/auth", method = RequestMethod.GET)
	public String auth(HttpServletRequest request, HttpServletResponse response){
		logger.info("获取微信授权用户信息开始................");
		
		try {
			
			String redirectUri = "";
			if(request.getParameter("redirect_uri")!=null)
				redirectUri = request.getParameter("redirect_uri").toString();
			int type = 2;
			StringBuilder urlBuilder = new StringBuilder();
			urlBuilder.append(AUTHORIZE_URL)
				.append("?appid=").append(WxConfig.appId)
				.append("&redirect_uri=").append(URLEncoder.encode(redirectUri, "UTF-8"))
				.append("&response_type=").append("code")
				.append("&scope=").append((type == 1 ? "snsapi_base" : "snsapi_userinfo"))
				.append("&state=").append("STATE")
				.append("#wechat_redirect");
			logger.info("微信授权链接: {}", urlBuilder);
			return "redirect:" + urlBuilder.toString();
		} catch(Exception e) {
			logger.error("获取微信授权用户信息异常", e.getMessage());
		}
		return null;
	}
    
    
	
    @ResponseBody
	@RequestMapping(value = "/callBack", method = RequestMethod.GET)
	public void callBack(HttpServletRequest request, HttpServletResponse response) {
		logger.info("获取微信回调获取用户信息开始................");
		try {
	   		String code = request.getParameter("code");
	   		logger.info("获取微信回调code={}", code);
	   		if(StringUtils.isNotBlank(code)) {
	   			Oauth2Token ot = userInfoService.getOauth2AccessToken(wxConfig.appId, wxConfig.appSecret, code);
		   		if(ot!=null) {
		   			if(ot.getOpenId()!=null) {
		   				logger.info("获取openid成功openid={}", ot.getOpenId());
		   				response.getWriter().print(ot.getOpenId());
		   			} else {
		   				logger.error("获取openid出错....");
		   			}
		   		}
	   		} else {
	   			logger.info("获取微信回调code is null");
	   		}
		} catch (Exception e) {
			logger.error("获取微信回调出错!", e.getMessage());
		}
		logger.info("获取微信回调结束");
	}
    
    /**
     * 微信接入
     */
    @RequestMapping(value="/connect",method = RequestMethod.GET)
    @ResponseBody
    public void connectWeixin(HttpServletRequest request, HttpServletResponse response) throws IOException{
        // 将请求、响应的编码均设置为UTF-8（防止中文乱码）  
        request.setCharacterEncoding("UTF-8");  
        response.setCharacterEncoding("UTF-8");
        //boolean isGet = request.getMethod().toLowerCase().equals("get"); 
      
        PrintWriter out = response.getWriter();
         
        try {
	        String signature = request.getParameter("signature");// 微信加密签名  
	        String timestamp = request.getParameter("timestamp");// 时间戳  
	        String nonce = request.getParameter("nonce");// 随机数  
	        String echostr = request.getParameter("echostr");//随机字符串  
	        
	        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败 
	        if (SignUtil.checkSignature(signature, timestamp, nonce)) {  
	            logger.info("Connect the weixin server is successful.{},{},{},{}", signature, timestamp, nonce, echostr);
	            out.write(echostr);
	            out.flush();
	        } else {  
	        	logger.error("Failed to verify the signature!"); 
	        }
        } catch (Exception e) {
        	logger.error("Connect the weixin server is error.", e);
        } finally {
        	out.close();
        }
    }
}
